<?php

/**
 * uniBoard ACP Imageset Import Page
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-15 17:35:38 +0000 (Wed, 15 Sep 2010) $
 * $Revision: 61 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_imp_images{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;

		// Upload?
		if ( $appCore -> _POST( 'upload') == 1)
		{
			// Import imageset
			$this -> doImport();	
		}
		else
		{
			// Draw form
			$this -> drawForm();
		}
		
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Performs import
	 *
	 */
	
	function doImport(){
		
		// Create file upload
		$data_file = new api_file_upload( $this -> appCore, 'data_file');
		
		// Configure uploaded
		$data_file -> setExtensions( array( '.xml', '.xml.gz'));
		$data_file -> setUploadSize( 12288);
		
		// Catch file
		$data_file -> catchFile();
		
		// Try-catch
		try
		{
			// Api has error?
			if ( $data_file -> error)
			{
				// Trow exception
				throw new exc_small( $data_file -> last_error);
			}
				
			// Detect if we uploaded file is GZIP compressed
			if ( strtolower( substr( $data_file -> getFileName(), strlen( $data_file -> getFileName()) - 7)) == '.xml.gz')
			{
				// Uncompress file
				if ( function_exists( 'gzfile'))
				{
					$data_file = join( '', gzfile( $data_file -> getFilePath()));
				}
				else
				{
					// Trow exception
					throw new exc_small( $this -> appCore -> lang['acp_imageset_import_gzip_not_avaiable']);
				}
			}
			else
			{
				// Simply load XML file contents
				$data_file = file_get_contents( $data_file -> getFilePath());
			}
			
			// We will handle errors
			libxml_use_internal_errors(false);
			
			// Create xml data file
			@$data = simplexml_load_string( $data_file);
			
			// Error?
			if ( $data === false)
			{
				// Trow exception
				throw new exc_small( $this -> appCore -> lang['acp_import_xml_corrupted']);
			}
			
			// Data is valid?
			if ( !isset( $data -> imageset_data) || !isset( $data -> imageset_data -> imageset_name) || !isset( $data -> imageset_images))
			{
				throw new exc_small( $this -> appCore -> lang['acp_import_xml_corrupted']);
			}
			
			// Set api
			$imageset = new api_imageset( $this -> appCore);
			
			// Fill it with data
			$imageset -> setImagesetName( base64_decode( $data -> imageset_data -> imageset_name));
			
			// Additional fields
			if ( isset( $data -> imageset_data -> imageset_author))
			{
				$imageset -> setImagesetAuthor( base64_decode( $data -> imageset_data -> imageset_author));
			}
			
			if ( isset( $data -> imageset_data -> imageset_email))
			{
				$imageset -> setImagesetEmail( base64_decode( $data -> imageset_data -> imageset_email));
			}
			
			if ( isset( $data -> imageset_data -> imageset_www))
			{
				$imageset -> setImagesetWww( base64_decode( $data -> imageset_data -> imageset_www));
			}
			
			// Api got incorrect settings?
			if ( $imageset -> error)
			{	
				// API has incorrect data from XML
				throw new exc_small( $this -> appCore -> lang['acp_import_xml_corrupted']);
			}
			
			// Create api
			$imageset -> saveData();
			
			// Create new directory for api
			class_files::newDir( STYLES_DATA_PATH . 'imageset_' . $imageset -> imageset_id);
			
			// File insert
			$insert_sql = array();
			
			// Reiterate images
			foreach ( $data -> imageset_images -> image as $image_data)
			{
				// Image has correct data?
				if ( isset( $image_data -> image_name) && isset( $image_data -> image_file) && isset( $image_data -> image_content) && isset( $image_data -> image_width) && isset( $image_data -> image_height))
				{
					// Decode data
					$image_name = base64_decode( $image_data -> image_name);
					$image_file = base64_decode( $image_data -> image_file);
					$image_file_content = base64_decode( $image_data -> image_content);
					$image_width = (int) base64_decode( $image_data -> image_width);
					$image_height = (int) base64_decode( $image_data -> image_height);
					
					// File content is good?
					if ( isset( $image_file_content[0]) && isset( $image_name[0]) && mb_strlen( $image_name) < 256)
					{
						// Fix width
						if ( $image_width < 1)
						{
							$image_width = 1;
						}
						
						// Fix height
						if ( $image_height < 1)
						{
							$image_height = 1;
						}
						
						// File name is allrite?
						$file_name = $this -> appCore -> secureFilename( substr( $image_file, 0, strpos( $image_file, '.')));
						$file_ext = strtolower( substr( $image_file, strpos( $image_file, '.')));
						
						// Extension checks out?
						if ( $file_ext == '.png' || $file_ext == '.gif' || $file_ext == '.jpeg' || $file_ext == '.jpg')
						{
							// Build complete filename
							$image_file = $file_name . $file_ext;
							
							// File name and extension is good?
							if ( isset( $image_file[0]) && mb_strlen( $image_file) < 256)
							{
								// Add file to massinsert
								$insert_sql[] = '\'' . $imageset -> imageset_id . '\', \'' . $this -> appCore -> db -> strEscape( $image_name) . '\', \'' . $this -> appCore -> db -> strEscape( $image_file) . '\', \'' . $image_width . '\', \'' . $image_height . '\'';
							
								// Make file
								file_put_contents( STYLES_DATA_PATH . 'imageset_' . $imageset -> imageset_id . '/' . $image_file, $image_file_content);
							}
						}
					}
				}
			}
			
			// Multiple insert?
			if ( !empty( $insert_sql))
			{
				$this -> appCore -> db -> multipleInsert( 'imageset_id, image_name, image_file, image_width, image_height', $insert_sql, 'imagesets_images');
			}
			
			// Create Log
			$this -> appCore -> logAdmin( 'log_admin_imported_imageset', htmlspecialchars( $this -> api -> imageset_name));
				
			// Stuff added, trow user to imagesets list
			$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=images'), $this -> appCore -> lang['acp_imageset_imported']);			
		}
		catch ( exc_small $error)
		{
			// Draw error
			$this -> appCore -> output -> error( $error -> message, $this -> appCore -> lang['acp_import_imageset']);
			
			// Repeat form
			$this -> drawForm();
		}
		
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Draws import form
	 *
	 */
	
	function drawForm(){
		
		// Start output buffer
		ob_start();
		
		// Load fields templates
		$this -> appCore -> templates['form_inputs'] = new tpl_form_inputs( $this -> appCore);
		
		// Open Form
		echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=imp_images'), '', true);
		echo $this -> appCore -> drawHidden( 'upload', 1);
		
		// Open Block
		echo $this -> appCore -> output -> openFormBlock();
		
		// Draw Field
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['import_imageset_file'], $this -> appCore -> drawFileUpload( 'data_file'), $this -> appCore -> lang['import_imageset_file_expl']);
		
		// Draw Submit Button
		echo $this -> appCore -> output -> submitButton( $this -> appCore -> lang['import_data']);
		
		// Close Block
		echo $this -> appCore -> output -> closeFormBlock();
		
		// Close Form
		echo $this -> appCore -> output -> closeForm();
		
		// Draw output
		$this -> appCore -> output -> draw( $this -> appCore -> lang['acp_import_imageset'], array(
			$this -> appCore -> adminLink( 'act=imp_images') => $this -> appCore -> lang['acp_import_imageset'],
		), ob_get_clean());
				
	}
	
}